

import java.io.IOException;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.RateControl;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author Jarrrgh
 */
public class Engine extends Thread implements PlayerListener {
    private Player player;
    private RateControl rateControl;
    private int throttle;

    private Timer timer;
    private TimerTask accelerate;
    private TimerTask decelerate;

    public Engine() {}

    public void run(){
        try{
            InputStream is= this.getClass().getResourceAsStream("/engine.wav");
            player= Manager.createPlayer(is , "audio/wav");
            player.realize();
            player.prefetch();            
            rateControl = (RateControl)player.getControl("RateControl");
            throttle = rateControl.getMinRate();
            rateControl.setRate(throttle);
            player.setLoopCount(-1);
            player.addPlayerListener(this);
        } catch (IOException ioe) {
        } catch (MediaException me) { }
    }

    public void on() {
       try {            
            player.start();            
        } catch (MediaException me) {}
    }

    public void off() {
        try {
            player.stop();
        } catch(MediaException me) { }
    }

    public void accelerate() {
        resetTimer();
        accelerate = new TimerTask() {
            public void run() {
                throttle += 4000;
                if(throttle < rateControl.getMaxRate()) {
                    rateControl.setRate(throttle);
                } else {                    
                    throttle = rateControl.getMaxRate();
                    rateControl.setRate(throttle);
                    this.cancel();
                }
            }
        };        
        timer.schedule(accelerate, 0, 40);
    }

    public void decelerate(){
        resetTimer();
        decelerate = new TimerTask() {
            public void run() {
                throttle -= 8000;
                if(throttle > rateControl.getMinRate()) {
                        rateControl.setRate(throttle);
                } else {
                    throttle = rateControl.getMinRate();
                    rateControl.setRate(throttle);
                    this.cancel();                    
                }
            }
        };
        timer.schedule(decelerate, 0, 40);
        
    }

    private void resetTimer() {        
        if(timer != null) {
            try {
                timer.cancel();
            } catch(Exception e) {}
        }        
        timer = new Timer();
    }

    public void playerUpdate(Player player, String event, Object eventData){
        if (event.equals(PlayerListener.END_OF_MEDIA)){            
            rateControl.setRate(throttle);
        }
    }
}